import easyquotation,sys,codecs
import numpy as np
import pandas as pd
from datetime import date,datetime,timedelta
import os
import glob
import datetime



try:
    quotation = easyquotation.use('tencent')
except:
    quotation = easyquotation.use('sina')

def ReadFile(filePath):
    with codecs.open(filePath, "r", "gb2312") as f:
        return f.read()
def WriteFile(filePath, u, encoding="utf-8"):
    # with codecs.open(filePath,"w",encoding) as f:
    with codecs.open(filePath, "wb") as f:
        f.write(u.encode(encoding, errors="ignore"))
# def CSV_2_UTF8(src, dst):
#     content = ReadFile(src)
#     WriteFile(dst, content, encoding="utf-8")
def CSV_2_UTF8(src, dst):
    content = ReadFile(src)
    WriteFile(dst, content, encoding="utf-8")

def tencentQuo(OQ代码,价格类型):
    # 获取委托价格
    # print(OQ代码)
    if ".SH" in OQ代码:
        腾讯代码="sh"+OQ代码[0:6]
    elif ".SZ" in OQ代码:
        腾讯代码="sz"+OQ代码[0:6]
    try:
        价格=quotation.real(腾讯代码)[腾讯代码[2:8]][价格类型]
    except Exception as e:
        print(e)
        价格=0
    return 价格

def 处理融券浮盈(资金账号,融券合约明细,保存地址):
    for index,row in 融券合约明细.iterrows():
        if row["合约类型"]==1 and row["未还合约数量"]>0:
            代码=row["securityID"]
            最新价=tencentQuo(代码,"now")
            # print(f"正在计算：{代码}")
            try:
                融券浮盈=(row["合约开仓金额"]/row["合约开仓数量"]-最新价)*(row["未还合约数量"])
                融券市值=最新价*row["未还合约数量"]
            except:
                融券浮盈=0
                融券市值=0
            融券合约明细.loc[index,"最新价"]=最新价
            融券合约明细.loc[index,"融券浮盈"]=融券浮盈
            融券合约明细.loc[index,"融券市值"]=融券市值
    累计融券浮盈=融券合约明细["融券浮盈"].sum()
    累计融券市值=融券合约明细["融券市值"].sum()

    print(f"已计算好{资金账号}融券浮盈/融券市值")
    return 累计融券浮盈,融券合约明细,累计融券市值

def 处理多头盈亏(资金账号,当前持仓,上个交易日持仓,保存地址,佣金模板):

    for index,row in 当前持仓.iterrows():
        # print(np.isnan(row['securityID']))
        # print(f"正在计算{资金账号}多头盈亏：{row['securityID']}")
        if row['securityID']!="":
            if row["当前数量"]==0 and row["盈亏金额"]==0:
                # try:
                资金账号,代码=row["账号"],row["securityID"]
                匹配记录成本价=上个交易日持仓[(上个交易日持仓["账号"]==资金账号) & (上个交易日持仓["securityID"]==代码) ]["成本价"].iloc[-1]
                盈亏金额=(row["卖出均价"]-匹配记录成本价)*row["今卖量"]
                # except Exception as e:
                #     print(f"计算失败原因：{e}")
                #     匹配记录成本价=0
                #     盈亏金额=0
                当前持仓.loc[index,"成本价"]=匹配记录成本价
                当前持仓.loc[index,"盈亏金额"]=盈亏金额
            # print(row["securityID"])
            昨收价=tencentQuo(row["securityID"],"close")
            佣金模板.columns=["资金账号","佣金率"]
            try:
                佣金率=佣金模板[佣金模板["资金账号"]==int(row["账号"])]["佣金率"].iloc[-1]
            except:
                佣金率=0.00015
            当日盈亏=row["当前数量"]*(row["最新价"]-昨收价)+(row["卖出均价"]-昨收价)*row["今卖量"]-(row["买入均价"]-昨收价)*row["今买量"]-row["买入均价"]*row["今买量"]*佣金率-row["卖出均价"]*row["今卖量"]*(佣金率+0.001)
            # print(row["securityID"],当日盈亏)
            当前持仓.loc[index,"昨收价"]=昨收价
            当前持仓.loc[index,"佣金率"]=佣金率
            当前持仓.loc[index,"当日盈亏"]=当日盈亏
        # #处理脏数据
        # if row['名称']=="":


    多头浮动盈亏=当前持仓[当前持仓["当前数量"]>0]["盈亏金额"].sum()
    多头平仓盈亏=当前持仓[当前持仓["当前数量"]==0]["盈亏金额"].sum()
    多头当日盈亏=当前持仓["当日盈亏"].sum()
    保存地址=保存地址.replace("positionInfo_"+date.today().strftime("%Y%m%d")+".csv","positionInfo_"+str(资金账号)+"_"+date.today().strftime("%Y%m%d")+".csv")
    当前持仓.to_csv(保存地址,index=False)
    print(f"已计算好{资金账号}多头浮盈")
    return 多头浮动盈亏,多头平仓盈亏,多头当日盈亏

def get_previous_workday(date):
    # 获取当前日期的星期几（0是周一，6是周日）
    weekday = date.weekday()

    # 如果当前是周一，则前一个工作日是周五
    if weekday == 0:
        previous_workday = date - timedelta(days=3)
    # 如果当前是周日，则前一个工作日是周五
    elif weekday == 6:
        previous_workday = date - timedelta(days=2)
    # 其他情况，前一个工作日是昨天
    else:
        previous_workday = date - timedelta(days=1)

    return previous_workday.strftime('%Y%m%d')

预处理数据目录=os.path.dirname(os.path.realpath(sys.argv[0]))

# 获取所有csv文件
csv_files = glob.glob(os.path.join(预处理数据目录, '*.csv'))

# 定义特定前缀
prefix持仓 = 'positionInfo_'
prefix合约 = 'compactInfo_'
# 获取特定前缀的csv文件
prefix_files持仓 = [file for file in csv_files if os.path.basename(file).startswith(prefix持仓)]
prefix_files合约 = [file for file in csv_files if os.path.basename(file).startswith(prefix合约)]
佣金模板文件 = [file for file in csv_files if os.path.basename(file).startswith('佣金模板')]
# 获取最近2个日期的数据
前日持仓路径=os.path.join(预处理数据目录,"positioninfo_"+get_previous_workday( datetime.datetime.now())+".csv")
今日持仓路径=os.path.join(预处理数据目录,"positioninfo_"+date.today().strftime("%Y%m%d")+".csv")
今日合约路径=os.path.join(预处理数据目录,"compactinfo_"+date.today().strftime("%Y%m%d")+".csv")
最近2持仓 = [前日持仓路径,今日持仓路径]
最近1合约 = [今日合约路径]
佣金信息=pd.read_csv(佣金模板文件[0], encoding='cp1252')
佣金信息.columns=["资金账号","佣金率"]
配置资金账号=佣金信息["资金账号"].tolist()


累计融券浮盈={}
累计融券市值={}
多头当日浮动盈亏={}
多头当日平仓盈亏={}
多头当日盈亏={}
for i in 配置资金账号:
    累计融券浮盈[str(i)]=0
    累计融券市值[str(i)]=0
    多头当日浮动盈亏[str(i)]=0
    多头当日平仓盈亏[str(i)]=0
    多头当日盈亏[str(i)]=0

if len(最近1合约)==1:
    print("开始计算融券累计浮盈")
    保存地址=最近1合约[0].replace("compactInfo_"+date.today().strftime("%Y%m%d")+".csv","【融券浮盈】compactInfo_"+date.today().strftime("%Y%m%d")+".csv")
    融券合约UTF地址=最近1合约[0].replace("compactInfo_","utf_compactInfo_")
    CSV_2_UTF8(最近1合约[0],融券合约UTF地址)
    # print(保存地址)
    融券合约=pd.read_csv(融券合约UTF地址, encoding='utf-8')
    融券合约["最新价"]=0
    融券合约["融券浮盈"]=0
    融券合约["融券市值"]=0
    汇总融券合约明细=pd.DataFrame(columns=["更新时间","账户类型","账户类型字典值","账号","合约类型","开仓日期","代码","securityID","名称","合约状态","合约开仓数量","合约开仓金额","合约开仓费用","合约总利息","未还合约数量","未还合约金额","未还合约息费","保证金比例","合约编号","归还截止日","续签到期日","最新价","融券浮盈","融券市值"])
    for 资金账号 in  配置资金账号:
        匹配记录=融券合约[融券合约["账号"]==资金账号]
        累计融券浮盈[str(资金账号)],融券合约明细,累计融券市值[str(资金账号)]=处理融券浮盈(资金账号,匹配记录,保存地址)
        汇总融券合约明细=pd.concat([汇总融券合约明细,融券合约明细])
        汇总融券合约明细.columns=["更新时间","账户类型","账户类型字典值","账号","合约类型","开仓日期","代码","securityID","名称","合约状态","合约开仓数量","合约开仓金额","合约开仓费用","合约总利息","未还合约数量","未还合约金额","未还合约息费","保证金比例","合约编号","归还截止日","续签到期日","最新价","融券浮盈","融券市值"]

    汇总融券合约明细.to_csv(保存地址,index=False)

else:
    print("不存在当前交易日的compactInfo文件，无法计算")

if len(最近2持仓)==2:
    print("开始计算多仓股票浮盈")
    #转化格式
    当天持仓UTF地址=最近2持仓[1].replace("positionInfo_","utf_positionInfo_")
    前天持仓UTF地址=最近2持仓[0].replace("positionInfo_","utf_positionInfo_")
    CSV_2_UTF8(最近2持仓[0],前天持仓UTF地址)
    CSV_2_UTF8(最近2持仓[1],当天持仓UTF地址)
    保存地址=最近2持仓[1].replace("positionInfo_"+date.today().strftime("%Y%m%d")+".csv","【多头浮盈】positionInfo_"+date.today().strftime("%Y%m%d")+".csv")
    # print(最近2持仓)
    当天持仓=pd.read_csv(当天持仓UTF地址)
    前天持仓=pd.read_csv(前天持仓UTF地址)
    当天持仓['securityID'] = 当天持仓['securityID'].fillna('')
    前天持仓['securityID'] = 前天持仓['securityID'].fillna('')

    当天持仓["昨收价"]=0
    当天持仓["佣金率"]=0
    当天持仓["当日盈亏"]=0
    for 资金账号 in  配置资金账号:
        匹配当天持仓=当天持仓[当天持仓["账号"]==资金账号]
        匹配前天持仓=前天持仓[前天持仓["账号"]==资金账号]

        多头当日浮动盈亏[str(资金账号)],多头当日平仓盈亏[str(资金账号)],多头当日盈亏[str(资金账号)]=处理多头盈亏(资金账号,匹配当天持仓,匹配前天持仓,保存地址,佣金信息)
else:
    print("不存在当前和上个交易日的positionInfo_文件，无法计算")
# print(f"未了结融券合约的融券浮盈：{round(累计融券浮盈,2)}\n"
#       f"多头当日浮动盈亏：{round(多头当日浮动盈亏,2)}\n"
#       f"多头当日平仓盈亏：{round(多头当日平仓盈亏,2)}\n"
#       f"多头当日盈亏：{round(多头当日盈亏,2)}\n"
#
#       )
盈亏数据=pd.DataFrame(columns=["生成时间","资金账号","融券累计盈亏","股票累计盈亏(不含清仓)","股票清仓浮盈","股票累计盈亏(含清仓)","股票当日浮盈"])
now = datetime.datetime.now()
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
for i in 配置资金账号:
    盈亏=[formatted_time,str(i),累计融券浮盈[str(i)],累计融券市值[str(i)],多头当日浮动盈亏[str(i)],多头当日平仓盈亏[str(i)],多头当日浮动盈亏[str(i)]+多头当日平仓盈亏[str(i)],多头当日盈亏[str(i)]]
    执行列表=pd.DataFrame([盈亏])
    执行列表.columns=["生成时间","资金账号","融券累计盈亏","融券累计市值","股票累计盈亏(不含清仓)","股票清仓浮盈","股票累计盈亏(含清仓)","股票当日浮盈"]
    盈亏数据=pd.concat([盈亏数据,执行列表])
数据保存地址="【统计结果】多空盈亏数据统计_"+date.today().strftime("%Y%m%d")+".csv"
盈亏数据.to_csv(数据保存地址, index=False)
for filename in os.listdir('.'):
    if filename.startswith('【UTF】'):
        os.remove(filename)

print("多头和空头的盈亏记录已生成到本地")
# filename = '/path/to/file.csv'  # 替换为您要打开的CSV文件路径
# os.system('wps' + 数据保存地址)
input("关闭重新运行")




